package b.cif.impl

import akka.Done
import b.cif.api.CC客户
import b.utils.entity.ACPersistentEntity

/**
  * 贲国称 于 16/12/12 创建。
  */
class C客户PersistentEntity extends ACPersistentEntity {

  override type Command = T客户Command
  override type Event = T客户Event
  override type State = CC客户State

  override def initialState: State = O客户State()

  override def behavior: Behavior = {
    case CC客户State(None, _) => notCreated
    case CC客户State(Some(_), _) => created
  }

  private val getCommand = Actions().onReadOnlyCommand[CC客户GetCommand, Option[CC客户]] {
    case (_, ctx, state) => ctx.reply(state.v客户)
  }

  private val notCreated = {
    Actions().onCommand[CC开客户Command, Done] {
      case (cmd: CC开客户Command, ctx, state) =>
        f命令处理(ctx, state.v客户.isDefined, s"客户[$entityId]已开立",
          ctx.thenPersist(CC新客户Event(cmd.v客户))(_ => ctx.reply(Done)))
    }.onEvent {
      case (event: CC新客户Event, _) => O客户State(event.v客户)
    }.orElse(getCommand)
  }

  private val created = {
    Actions().onCommand[CC申请账号Command, Int] {
      case (_, ctx, state) =>
        ctx.thenPersist(CC客户新账户序号Event(state.v账户序号 + 1))((event: CC客户新账户序号Event) => ctx.reply(event.v序号))
    }.onCommand[CC开客户Command, Done](f命令Done).onEvent {
      case (event: CC客户新账户序号Event, state) => state.f更新账户序号(event.v序号)
    }.orElse(getCommand)
  }

}
